package com.jx.mlxg.filter;

<<<<<<< HEAD
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
=======
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jx.mlxg.utils.JwtUtil;
import com.jx.mlxg.utils.ResponseResult;
>>>>>>> eb72a42842a7e02f996c4f2d21dc4051aa14ecf1
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
<<<<<<< HEAD
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Value("${security.jwt.secret-key}")
    private String secretKey;
=======
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;

@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;
>>>>>>> eb72a42842a7e02f996c4f2d21dc4051aa14ecf1

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
<<<<<<< HEAD

        String token = extractToken(request);
        if (token != null && !token.isEmpty()) {
            try {
                log.info("token---->{}", token);
                DecodedJWT decodedJWT = verifyToken(token);
                String openId = decodedJWT.getSubject(); // 正确获取subject（即openId）

                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(openId, null, null);
                SecurityContextHolder.getContext().setAuthentication(authentication);

            } catch (JWTVerificationException e) {
                // 检查是否是过期异常
                if (e.getMessage().contains("expired")) {
                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_PAYMENT_REQUIRED); // 402状态码
                    response.getWriter().write("{ \"code\": 402, \"message\": \"Token已过期\" }");
                } else {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "无效的Token"); // 403状态码
                }
                SecurityContextHolder.clearContext();
                return; // 阻止请求继续处理
            }
        }

        filterChain.doFilter(request, response);
    }

    private String extractToken(HttpServletRequest request) {
        String header = request.getHeader("jxToken");
        if (header != null) {
            // 如果前端传递的 token 没有 "Bearer " 前缀，则直接返回
            if (!header.startsWith("Bearer ")) {
                return header;
            }
            // 如果前端传递的 token 有 "Bearer " 前缀，则去掉前缀
            return header.substring(7);
        }
        return null;
    }

    private DecodedJWT verifyToken(String token) throws JWTVerificationException {
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        return JWT.require(algorithm)
                .build()
                .verify(token);
=======
        String servletPath = request.getServletPath();
        log.info("Request path: {}", servletPath);
        // 跳过登录接口，防止重复验证
        if (servletPath.startsWith("/login/") || servletPath.startsWith("/materialrequest/")) {
            log.info("Skipping JWT validation for path: {}", servletPath); // 添加日志
            filterChain.doFilter(request, response);
            return;
        }

        try {
            // 从请求头中获取 Token
            String token = request.getHeader("Authorization");

            // 验证 Token
            if (validateToken(token)) {
                // 验证通过，设置用户信息到 Spring Security 上下文
                UsernamePasswordAuthenticationToken auth =
                        new UsernamePasswordAuthenticationToken(
                                jwtUtil.getUsernameFromToken(token),
                                null,
                                new ArrayList<>()
                        );
                log.info("jwt解析的token结果: {}",auth);
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        } catch (Exception e) {
            // 验证失败，返回错误响应
            ResponseResult<Object> errorResponse =
                    ResponseResult.failure("无效的 Token 或 Token 已过期");
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(errorResponse));
            return;
        }

        // 继续处理请求
        filterChain.doFilter(request, response);
    }

    private boolean validateToken(String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return false;
        }

        token = token.substring(7); // 去掉 "Bearer " 前缀

        try {
            // 解析 Token 并验证
            return jwtUtil.validateToken(token);
        } catch (Exception e) {
            return false;
        }
>>>>>>> eb72a42842a7e02f996c4f2d21dc4051aa14ecf1
    }
}
